<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI助手</title>
    <script src="/links/polyfill.min.js"></script>
    <script src="/links/axios/axios.min.js"></script>
    <script src="/links/vue/vue.min.js"></script>
    <script src="/links/element-ui/index.js"></script>
    <link href="/links/element-ui/theme/index.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/go.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/marked/15.0.6/marked.min.js"></script>
    <script src="/js/HttpApi.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
        }

        body {
            background-color: #f5f5f5;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        #chat-container {
            flex: 1;
            margin: 0 auto;
            width: 100%;
            padding: 20px;
            overflow-y: auto;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            gap: 15px;
        }

        .user-message {
            flex-direction: row-reverse;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 5px;
            background-color: #eee;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }

        .content {
            padding: 12px 16px;
            border-radius: 8px;
            line-height: 1.6;
            max-width: calc(100% - 50px);
        }

        .user-content {
            background-color: #ebf3ff;
            color: #1a1a1a;
        }

        .assistant-content {
            background-color: #fff;
            border: 1px solid #e5e5e5;
        }

        #input-container {
            background-color: #fff;
            padding: 10px 20px 20px;
            display: flex;
            gap: 10px;
        }

        #user-input {
            flex: 1;
            padding: 12px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            resize: none;
            min-height: 44px;
            max-height: 200px;
        }

        button {
            padding: 0 20px;
            height: 44px;
            background-color: #0d6efd;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0b5ed7;
        }

        .loading {
            text-align: center;
            color: #666;
            padding: 10px;
        }

        .content.assistant-content li {
            margin-left: 16px;
            margin-bottom: 13px;
        }

        .content.assistant-content {
            width: calc(100% - 50px);
        }

        pre {
            background-color: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #ddd;
            overflow-x: auto;
            max-height: 450px;
            /* 设置最大高度 */
            overflow-y: auto;
            /* 允许垂直滚动 */
            position: relative;
        }

        h3 {
            font-size: 18px;
            line-height: 1.5;
            margin: 18px 0 13px;
            font-weight: 600;
        }

        p {
            white-space: pre-wrap;
        }

        /* 添加表格边框样式 */
        table {
            border-collapse: collapse;
            width: 100%;
        }

        th,
        td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        #role-selection {
            padding: 10px 20px 0px;
            background-color: #FFFFFF;
            border-top: 1px solid #e5e5e5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        #role-selection button {
            margin-right: 10px;
            background-color: #f0f0f0;
            color: #333;
            padding: 2px 20px;
            height: 36px;
        }

        #role-selection button.selected {
            background-color: #0d6efd;
            color: white;
        }
    </style>
</head>

<body>
<div id="chat-container">
    <div class="message">
        <div class="avatar">AI</div>
        <div class="content assistant-content">您好，我是您的AI助理，有什么可以帮您的？</div>
    </div>
</div>

<div id="role-selection">
    <div>
        <button data-role="document" onclick="selectRole(this)">功能设计</button>
        <button data-role="sql" onclick="selectRole(this)">生成表结构</button>
        <button data-role="coding" onclick="selectRole(this)">生成代码</button>
        <button data-role="debug" onclick="selectRole(this)">功能测试</button>
    </div>
    <div>
        <button id="clear-button" onclick="clearChat()">清理屏幕</button>
        <button id="new-button" onclick="newChat()">新建会话</button>
    </div>
</div>

<div id="input-container">
    <textarea id="user-input" placeholder="输入您的问题..." rows=2 onkeydown="handleKeyDown(event)"></textarea>
    <button onclick="handleSend()">发送</button>
</div>

<script>
    let selectedRoleButton = null;
    let chatId = null;

    function selectRole(button) {
        if (selectedRoleButton === button) {
            // 如果点击的是已选中的按钮，则取消选择
        } else {
            // 取消之前选中按钮的选中状态
            if (selectedRoleButton) {
                selectedRoleButton.classList.remove('selected');
            }
            // 设置新的选中按钮
            button.classList.add('selected');
            selectedRoleButton = button;
            initRoleMessage();
        }
    }

    async function handleSend() {
        const inputEl = document.getElementById('user-input');
        const question = inputEl.value.trim();
        if (!question) return;
        addMessage(question, 'user');
        inputEl.value = '';
        inputEl.style.height = 'auto';

        const formData = new FormData();
        formData.append('message', question);
        formData.append('chatId', chatId);
        if (selectedRoleButton) {
            const selectedRole = selectedRoleButton.dataset.role;
            formData.append('role', selectedRole);
        }

        HttpApi.submitForm("/autocode/assistants/chat",formData, function(res){
            chatId = res.chatId;
            addMessage(res.content, 'assistant');
        });
    }

    function addMessage(content, role) {
        const container = document.getElementById('chat-container');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role === 'user' ? 'user-message' : ''}`;
        container.appendChild(messageDiv);
        const roleDiv = document.createElement('div');
        roleDiv.className = "avatar";
        roleDiv.innerHTML = `
                ${role === 'user' ? 'You' : 'AI'}
            `;

        const contentDiv = document.createElement('div');
        contentDiv.className = `content ${role === 'user' ? 'user-content' : 'assistant-content'}`;
        messageDiv.appendChild(roleDiv);
        messageDiv.appendChild(contentDiv);
        const htmlContent = marked.parse(content);
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlContent, 'text/html');
        const elements = Array.from(doc.body.childNodes);
        traverseAndAppend(elements, contentDiv);
    }

    function initMessage(content, role) {
        const container = document.getElementById('chat-container');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role === 'user' ? 'user-message' : ''}`;
        container.appendChild(messageDiv);
        const roleDiv = document.createElement('div');
        roleDiv.className = "avatar";
        roleDiv.innerHTML = `
                ${role === 'user' ? 'You' : 'AI'}
            `;

        const contentDiv = document.createElement('div');
        contentDiv.className = `content ${role === 'user' ? 'user-content' : 'assistant-content'}`;
        messageDiv.appendChild(roleDiv);
        messageDiv.appendChild(contentDiv);
        const htmlContent = marked.parse(content);
        contentDiv.innerHTML =htmlContent;
    }


    async function traverseAndAppend(elements, parent) {
        for (let index = 0; index < elements.length; index++) {
            let element = elements[index];
            if (element.childNodes.length > 0) {
                let cloneElement = element.cloneNode(false);
                parent.appendChild(cloneElement);
                await traverseAndAppend(element.childNodes, cloneElement)
            } else {
                if (parent.tagName === "CODE" && parent.className && element.nodeType === Node.TEXT_NODE) {
                    let lines = element.textContent.split('\n');
                    for (let lineRow = 0; lineRow < lines.length; lineRow++) {
                        if (lineRow == 0 && lines[lineRow] == '') {
                            continue;
                        }
                        parent.insertAdjacentText('beforeend', lines[lineRow]);
                        parent.insertAdjacentText('beforeend', '\n');
                        scrollToBottom();
                        await sleep(20);
                    }
                    hljs.highlightAll();
                } else {
                    let cloneElement = element.cloneNode(true);
                    parent.appendChild(cloneElement);
                    scrollToBottom();
                    await sleep(50);
                }

            }
        }
    }


    //hljs.highlightAll();
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }


    function handleKeyDown(event) {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            handleSend();
        }
    }

    function scrollToBottom() {
        const container = document.getElementById('chat-container');
        container.scrollTop = container.scrollHeight;
    }

    // 自动调整输入框高度
    document.getElementById('user-input').addEventListener('input', function () {
        this.style.height = 'auto';
        this.style.height = this.scrollHeight + 'px';
    });

    function initRoleMessage() {
        const selectedRole = selectedRoleButton.dataset.role;
        if (selectedRole === 'sql') {
            const chatContainer = document.getElementById('chat-container');
            chatContainer.innerHTML = '';
        }else{
            clearChat();
        }
        //设置默认角色
        HttpApi.post('/autocode/assistants/roleMessage',{"role":selectedRole,"chatId":chatId},function (res) {
            if (res) {
                res.forEach(message => {
                    if (message.role !== 'system') {
                        initMessage(message.content, message.role);
                    }
                });
            }else{

            }
        });

    }

    // 页面加载完成后设置默认角色
    window.onload = function () {
        const defaultRoleButton = document.querySelector('button[data-role="document"]');
        if (defaultRoleButton) {
            if (selectedRoleButton) {
                selectedRoleButton.classList.remove('selected');
            }
            // 设置新的选中按钮
            defaultRoleButton.classList.add('selected');
            selectedRoleButton = defaultRoleButton;
        }
        //设置默认角色
        HttpApi.post('/autocode/assistants/getLastChat',{},function (res) {
            console.log(res);
            if (res && res.messages) {
                res.messages.forEach(message => {
                    if (message.role !== 'system') {
                        initMessage(message.content, message.role);
                    }
                });
                chatId = res.chatId;
            }
        });
    };

    function clearChat() {
        const chatContainer = document.getElementById('chat-container');
        chatContainer.innerHTML = '';
        const initialMessage = document.createElement('div');
        initialMessage.className = 'message';
        const avatarDiv = document.createElement('div');
        avatarDiv.className = 'avatar';
        avatarDiv.textContent = 'AI';
        const contentDiv = document.createElement('div');
        contentDiv.className = 'content assistant-content';
        contentDiv.textContent = '您好，我是您的AI助理，有什么可以帮您的？';
        initialMessage.appendChild(avatarDiv);
        initialMessage.appendChild(contentDiv);
        chatContainer.appendChild(initialMessage);
    }

    function newChat(){
        HttpApi.postConfirm('/autocode/assistants/clearChat', {"chatId":chatId},function(res){
            clearChat();
            chatId = null;
            //设置角色
            const defaultRoleButton = document.querySelector('button[data-role="document"]');
            if (defaultRoleButton) {
                selectRole(defaultRoleButton);
            }
        });
    }
</script>
</body>

</html>